package leetcode.str;

public class Test151 {

    public static void main(String[] args) {
        String s = reverseWords("a good   example");
        System.out.println(s);
    }

    public static String reverseWords(String s) {
        char[] chars = s.toCharArray();
        int left = 0,right = chars.length-1;
        while (left<= right){
            char t = chars[left];
            chars[left] = chars[right];
            chars[right] = t;
            left++;
            right--;
        }
        int i = 0;
        while (i<chars.length){
            if (chars[i] == ' '){
                i++;
                continue;
            }
            int start = i, end = i;
            while (end<chars.length-1 && chars[end+1] != ' '){
                end++;
            }
            i = end+1;
            while (start<=end){
                char t = chars[start];
                chars[start] = chars[end];
                chars[end] = t;
                start++;
                end--;
            }
        }

        return new String(chars);
    }
}
